package main

import (
	"fmt"
	"golang.org/x/crypto/ssh/knownhosts"
	"html/template"
	"io"
	"net/http"
	"os"
	"sync"
	"sync/atomic"
	"time"
)

type Person struct {
	Name    string
	Age     int
	Emails  []string
	Company string
	Role    string
}

type OnlineUser struct {
	User      []*Person
	LoginTime string
}

type Session interface {
	Set(key, value interface{})
	Get(key interface{}) interface{}
	Remove(key interface{}) error
	GetId() string
}
type SessionFromMemory struct {
	sid              string
	lock             sync.Mutex
	lastAccessedTime time.Time
	maxAge           int64
	data             map[interface{}]interface{}
}

func newSessionFromMemory() *SessionFromMemory {
	return &SessionFromMemory{
		data:   make(map[interface{}]interface{}),
		maxAge: 60 * 30,
	}
}
func (si *SessionFromMemory) Get(key interface{}) interface{} {
	if value := si.data; value != nil {
		return value
	}
	return nil
}
func (si *SessionFromMemory) Set(key, value interface{}) {
	si.lock.Lock()
	defer si.lock.Unlock()
	si.data[key] = value
}
func (si *SessionFromMemory) Remove(key interface{}) error {
	if value := si.data[key]; value != nil {
		delete(si.data, key)
	}
	return nil
}
func (si *SessionFromMemory) GetId() string {
	return si.sid
}

func Handler(w http.ResponseWriter, r *http.Request) {
	dumx := Person{
		Name:    "zoro",
		Age:     27,
		Emails:  []string{"dg@gmail.com", "dk@hotmail.com"},
		Company: "Omron",
		Role:    "SE"}

	chxd := Person{Name: "chxd", Age: 27, Emails: []string{"test@gmail.com", "d@hotmail.com"}}

	onlineUser := OnlineUser{User: []*Person{&dumx, &chxd}}

	//t := template.New("Person template")
	//t, err := t.Parse(templ)
	t, err := template.ParseFiles("views/tmpl.html", "views/top.html")
	checkError(err)

	err = t.Execute(w, onlineUser)
	checkError(err)
}
func TT(w http.ResponseWriter, r *http.Request) {
	test := r.PostFormValue("test")
	fmt.Println(r.Cookies())
	se := new(SessionFromMemory)
	io.WriteString(w, test)
}
func main() {
	http.HandleFunc("/", Handler)
	http.HandleFunc("/test", TT)
	http.ListenAndServe(":8888", nil)
}

func checkError(err error) {
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
		os.Exit(1)
	}
}
